package list;

/**
 * @author Jisheng Huang
 * @version 20250613
 */
public class SwapNodeInList_1721 {
    /**
     * 找到倒数第k个节点和第k个节点后进行值交换
     *
     * @param head the list
     * @param k    the kth number
     * @return the modified list
     */
    public static ListNode swapNodes(ListNode head, int k) {
        ListNode left = head;
        ListNode right = head;

        for (int i = 1; i < k; ++i) {
            left = left.next;
        }

        ListNode cur = left;

        while (cur.next != null) {
            right = right.next;
            cur = cur.next;
        }

        int temp = right.val;
        right.val = left.val;
        left.val = temp;

        return head;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode h1 = new ListNode(2);
        ListNode h2 = new ListNode(3);
        ListNode h3 = new ListNode(4);
        ListNode h4 = new ListNode(5);
        head.next = h1;
        h1.next = h2;
        h2.next = h3;
        h3.next = h4;

        System.out.println(swapNodes(head, 2));
    }


    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        public String toString() {
            return val + (next != null ? "->" + next : "");
        }
    }
}

